// 在某个 utils 文件中定义指令
import { type Directive, type DirectiveBinding, nextTick } from "vue";

interface ResizeCallback {
  (dimensions: { width: number; height: number }): void;
}

export const resize: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<ResizeCallback>) {
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        if (binding.value) {
          binding.value({ width, height }); // 调用绑定的回调函数
        }
      }
    });

    nextTick(() => {
      resizeObserver.observe(el); // 开始观察目标元素
    });

    el.__resizeObserver__ = resizeObserver; // 保存 ResizeObserver 实例
  },
  beforeUnmount(el: HTMLElement) {
    if (el.__resizeObserver__) {
      el.__resizeObserver__.disconnect(); // 停止观察
      el.__resizeObserver__ = null;
    }
  },
};
